package com.vcredit.creditcat.service.product.sd;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.vcredit.creditcat.util.ConcurrentDateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.enumtype.AuthItemEnum;
import com.vcredit.creditcat.enumtype.auth.SupplementItemEnum;
import com.vcredit.creditcat.enumtype.product.sd.SDMarriageEnum;
import com.vcredit.creditcat.enumtype.product.sd.SDPrefessionEnum;
import com.vcredit.creditcat.enumtype.product.sd.SDSalaryEnum;
import com.vcredit.creditcat.model.AddressList;
import com.vcredit.creditcat.model.AuthPersonalAddress;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.CustProductApply;
import com.vcredit.creditcat.model.CustSupplementItem;
import com.vcredit.creditcat.model.Relative;
import com.vcredit.creditcat.model.base.AbstractItem;
import com.vcredit.creditcat.service.product.IProductApplyNewService;
import com.vcredit.creditcat.service.product.shared.ProductApplyServiceAdaptor;
import com.vcredit.creditcat.util.JsonUtil;
import com.vcredit.creditcat.util.Utility;
import com.vcredit.creditcat.vo.ProductApplyResultVo;
import com.vcredit.creditcat.vo.auth.AuthIdentityExt;
import com.vcredit.creditcat.vo.auth.AuthMobileExt;
import com.vcredit.creditcat.vo.auth.AuthPersonalInfoExt;
import com.vcredit.creditcat.vo.auth.AuthSecreditExt;
import com.vcredit.creditcat.vo.auth.RelativeListExt;
import com.vcredit.creditcat.vo.product.sd.CreditCust;
import com.vcredit.creditcat.vo.product.sd.SDAddress;
import com.vcredit.creditcat.vo.product.sd.SDCreditMobile;
import com.vcredit.creditcat.vo.product.sd.SDQueryParamVo;
import com.vcredit.creditcat.vo.product.sd.SDQueryResultVo;
import com.vcredit.creditcat.vo.product.sd.SDRelation;
import com.vcredit.creditcat.vo.product.sd.SDResultVo;
import com.vcredit.creditcat.vo.product.sd.SDUserCreditInfoVo;
import com.vcredit.creditcat.vo.product.xyh.CreditZmxy;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;

/***
 * 闪贷申请实现类
 *
 */
@Service(ProductApplyServiceAdaptor.BEANNAME_PREFIX + 3)
public class SDApplyServiceImpl implements IProductApplyNewService{
	
private  Logger logger = LoggerFactory.getLogger(SDApplyServiceImpl.class);
	
	private static final Integer TIMEOUT = 60; // 请求超时时间60s
	
	public static final String CUST_PREFIX = "creditcat_";
	
	@Value("${product.sd.queryUrl}")
	private String queryUrl;
	
	@Value("${product.sd.creditUrl}")
	private String creditUrl;
	
	@Value("${resource.image.url}")
	private String imagUrl;

	@Log
	@Override
	public ProductApplyResultVo apply(Map<Integer, AbstractItem> custAuthInfoMap, 
			Map<Long, CustSupplementItem> custSupplementItemMap, Map<String,Object> otherParams) {
		try {
			/**
			 * 1、取出认证项数据
			 **/
			Cust cust = (Cust) otherParams.get("cust");
			CustSupplementItem supplement;
			if(custSupplementItemMap.get(SupplementItemEnum.SD_BASE_INFO.getItemId())!=null){
				supplement = custSupplementItemMap.get(SupplementItemEnum.SD_BASE_INFO.getItemId());
			}else{
				supplement = custSupplementItemMap.get(SupplementItemEnum.Common_BASE_INFO.getItemId());
			}
			AuthPersonalInfoExt personalInfo = JacksonUtil.Json2Obj(supplement.getDataEntity(), new TypeReference<AuthPersonalInfoExt>() {
			});
			AuthIdentityExt identity = (AuthIdentityExt) custAuthInfoMap.get(AuthItemEnum.VERIFY_FACE_PAIR.getCode());
			AuthMobileExt authMobile = (AuthMobileExt) custAuthInfoMap.get(AuthItemEnum.MOBILE.getCode());
			RelativeListExt relativeListVo = (RelativeListExt) custAuthInfoMap.get(AuthItemEnum.CONTACTS.getCode());
			AuthSecreditExt secredit = (AuthSecreditExt) custAuthInfoMap.get(AuthItemEnum.SESAME_CREDIT.getCode());

			/**
			 * 2、处理撞库和授信状态
			 **/
			SDQueryParamVo queryParam = new SDQueryParamVo(cust.getCustIdno(), cust.getCustName(), authMobile.getMobile());
			String queryParamStr = JacksonUtil.Obj2Json(queryParam);
			logger.info("闪贷查询状态入参：" + queryParamStr);
			String queryResultStr = HttpRequest.doJson(queryUrl, queryParamStr, TIMEOUT);
			logger.info("闪贷查询状态出参：" + queryResultStr);
			SDResultVo<SDQueryResultVo> result = JacksonUtil.Json2Obj(queryResultStr, new TypeReference<SDResultVo<SDQueryResultVo>>() {
			});

			CustProductApply custProductApply = new CustProductApply();
			if (!"1".equals(result.getStatus())) {
				String msg = "系统异常，请稍后重试";
				if (null != result.getMessage() && result.getMessage().length() < 20) {
					msg = result.getMessage();
				}
				if (msg.equals("年龄需在20-50岁之间")) {
					custProductApply.setAuditResult(0);
					custProductApply.setRejectMsg("闪贷提交失败：" + msg);
					custProductApply.setIsApply(false);
					return new ProductApplyResultVo(custProductApply);
				}
				return new ProductApplyResultVo(msg);
			}

			if (result.getData() != null) {
				SDQueryResultVo content = result.getData();
				int state = content.getOrderState();
				switch (state) {
					case 1:
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("闪贷黑名单！");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					case 2:
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("账号已存在");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					case 3:
						custProductApply.setAuditResult(2);
						custProductApply.setRejectMsg("闪贷手机认证中");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					case 4:
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("闪贷手机认证失败");
						custProductApply.setIsApply(true);
						custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
						return new ProductApplyResultVo(custProductApply);
					case 5:
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("闪贷手机认证未实名");
						custProductApply.setIsApply(true);
						custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
						return new ProductApplyResultVo(custProductApply);
					case 6:
						custProductApply.setAuditResult(2);
						custProductApply.setRejectMsg("授信中");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					case 7:
						custProductApply.setAuditResult(1);
						custProductApply.setIsApply(false);
						custProductApply.setRejectMsg("闪贷授信成功");
						custProductApply.setCreditAmt(content.getCreditAmt() == null ? 0 : content.getCreditAmt());
						if (content.getCreditExpiretime() != null) {
							long time = content.getCreditExpiretime();
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							String creditExpiredTime = format.format(time);
							custProductApply.setCreditExpiretime(creditExpiredTime);
						}
						custProductApply.setServiceRate(content.getServiceRate());
						custProductApply.setFormalitiesRate(content.getFormalitiesRate());
						custProductApply.setInterestRateMonthly(content.getInterestRateMonthly());
						return new ProductApplyResultVo(custProductApply);
					case 8:
						custProductApply.setAuditResult(0);
						if (StringUtils.isEmpty(content.getRemark())) {
							custProductApply.setRejectMsg("闪贷授信拒绝");
						} else {
							custProductApply.setRejectMsg("闪贷授信拒绝：" + content.getRemark());
						}
						custProductApply.setIsApply(true);
						custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
						return new ProductApplyResultVo(custProductApply);
					case 9:
						custProductApply.setAuditResult(7);
						custProductApply.setRejectMsg("闪贷信用补救");
						custProductApply.setIsApply(false);
						return new ProductApplyResultVo(custProductApply);
					case 10:
						custProductApply.setAuditResult(0);
						custProductApply.setRejectMsg("闪贷账号冻结");
						custProductApply.setIsApply(true);
						custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
						return new ProductApplyResultVo(custProductApply);
					default:
						break;
				}
			}
			/**
			 * 3、提交用户信息 
			 */
			SDUserCreditInfoVo creditInfo = new SDUserCreditInfoVo();
			//高级实名
			creditInfo.setCustId(CUST_PREFIX + cust.getCustId());
			creditInfo.setCustIdno(cust.getCustIdno());
			creditInfo.setCustName(cust.getCustName());
			creditInfo.setCustMobile(authMobile.getMobile());

			CreditCust creditCust = new CreditCust();

			for (AuthPersonalAddress address : personalInfo.getPersonalAddrList()) {
				if (address.getAddressType() == 0) {//公司地址
					creditCust.setWorkCity(address.getCity());
				}
				creditCust.setFullAddress(address.getGeoAddress());
			}

			if (personalInfo.getMarriageKey() == 1) {
				creditCust.setMarriage(SDMarriageEnum.WH.getCode());
			} else if (personalInfo.getMarriageKey() == 2) {
				creditCust.setMarriage(SDMarriageEnum.YH.getCode());
			} else if (personalInfo.getMarriageKey() == 3) {
				creditCust.setMarriage(SDMarriageEnum.LH.getCode());
			} else {
				creditCust.setMarriage(SDMarriageEnum.QT.getCode());
			}

			creditCust.setEducation(personalInfo.getEducationKey());

			int professionKey;
			if (personalInfo.getProfessionKey() <= 9) {
				professionKey = SDPrefessionEnum.SBZ.getCode();
			} else if (personalInfo.getProfessionKey() == 10) {
				professionKey = SDPrefessionEnum.SYYZ.getCode();
			} else if (personalInfo.getProfessionKey() == 11) {
				professionKey = SDPrefessionEnum.QYLB.getCode();
			} else {
				professionKey = SDPrefessionEnum.QT.getCode();
			}
			creditCust.setProfessional(professionKey);

			// 收入
			creditCust.setSalary(SDSalaryEnum.getTcodeByScode(personalInfo.getSalaryKey()));

			creditInfo.setCreditCust(creditCust);
			//手机认证
			SDCreditMobile mobile = new SDCreditMobile();

			mobile.setMobileId(authMobile.getMobileId());
			mobile.setWebsite(authMobile.getWebsite());
			creditInfo.setCreditMobile(mobile);
			//芝麻信用
			CreditZmxy zmxy = new CreditZmxy();
			zmxy.setZmxyScore(secredit.getZmxyScore());
			creditInfo.setCreditZmxy(zmxy);

			//紧急联系人
			List<SDRelation> relationList = new ArrayList<SDRelation>();
			for (Relative relative : relativeListVo.getRelativeList()) {
				SDRelation relation = new SDRelation();
				relation.setMobileNo(relative.getRelationMobile());
				if (StringUtils.isNotEmpty(relative.getRelationName())) {
					relation.setName(relative.getRelationName());
					relationList.add(relation);
				}
			}
			if (Utility.isNullOrEmpty(relationList)) {
				logger.error("紧急联系人不能为空:" + JsonUtil.obj2Json(relativeListVo, false));
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("闪贷提交失败：紧急联系人不能为空！");
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
				return new ProductApplyResultVo(custProductApply);
			}
			creditInfo.setCustRelationList(relationList);

			//通讯录
			List<SDAddress> addressBookList = new ArrayList<SDAddress>();
			for (AddressList address : relativeListVo.getAddressList()) {
				SDAddress sdAddress = new SDAddress();
				sdAddress.setContactNumber(address.getMobile());
				if (StringUtils.isNotEmpty(address.getName())) {
					sdAddress.setName(address.getName());
					addressBookList.add(sdAddress);
				}
			}
			if (addressBookList.size() <= 30) {
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("闪贷提交失败：通讯录联系人个数不能少于30个！");
				custProductApply.setIsApply(true);
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
				return new ProductApplyResultVo(custProductApply);
			}
			creditInfo.setCustAddressList(addressBookList);

			String submitParam = JacksonUtil.Obj2Json(creditInfo);

			logger.info("------------闪贷提交参数：" + submitParam);

			String submitResultStr = HttpRequest.doJson(creditUrl, submitParam, TIMEOUT);

			logger.info("------------闪贷提交结果：" + submitResultStr);

			SDResultVo<Object> submitresult = JacksonUtil.Json2Obj(submitResultStr, new TypeReference<SDResultVo<Object>>() {
			});
			if ("1".equals(submitresult.getStatus())) { // 提交成功
				custProductApply.setAuditResult(2);
				custProductApply.setRejectMsg("闪贷授信中");
				custProductApply.setIsApply(false);
				custProductApply.setCreditApplyTime("");
				return new ProductApplyResultVo(custProductApply);
			} else if ("000".equals(submitresult.getStatus())) { // 接口异常
				return new ProductApplyResultVo("系统异常，请稍后再试");
			} else {
				custProductApply.setAuditResult(0);
				custProductApply.setRejectMsg("闪贷提交失败：" + submitresult.getMessage());
				custProductApply.setIsApply(true);
				//可申请时间待定
				custProductApply.setCreditApplyTime(ConcurrentDateUtil.formatDateTime(ConcurrentDateUtil.addDayTime(new Date(), 30)));
				return new ProductApplyResultVo(custProductApply);
			}

		} catch (Exception e) {
			logger.error("闪贷申请异常", e);
			return new ProductApplyResultVo("闪贷申请异常！");
		}
	}

}
